import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify';
import * as echarts from '../../ec-canvas/echarts.js';

const app = getApp()
const db = wx.cloud.database()
let option;
let chartLine;
Page({
  data: {
    ec: {
      onInit: function (canvas, width, height){
          //初始化echarts元素，绑定到全局变量，方便更改数据
          chartLine = echarts.init(canvas, null, {
              width: 1000,
              height: 300
          });
          canvas.setChart(chartLine);
          //可以先不setOption，等数据加载好后赋值，
          //不过那样没setOption前，echats元素是一片空白，体验不好，所有我先set。
          
          chartLine.setOption(option);
      }
  },
    
    showAdmin: false,
    showModifyUser: false,
    hasUserInfo: false,
    avatarUrl:"",
    nickName:"",
    hasUserInformation:false,
    isAdmin:false,
    user_information:{
      name: '',
      student_number: '',
      openId: null,
      identity: '学生'
    },
    ModifyUser:{
      name: null,
      student_number: null
    }
  },
  //展开管理员界面
  showAdmin(){
    this.setData({
      showAdmin: true
    })
  },
  onClose(){
    this.setData({
      showAdmin: false,
      showModifyUser:false
    })
  },
  //显示用户修改信息界面
  showModifyUser(){
    this.setData({
      showModifyUser: true
    })
  },
  //注册输入姓名时触发
  name_change(e){
    this.setData({
      ['user_information.name'] : e.detail.value
    })
  },
  //修改信息 输入姓名时触发
  name_Modify(e){
    this.setData({
      ['ModifyUser.name'] : e.detail.value
    })
  },
  //注册输入学号时触发
  stuent_number_change(e){
    this.setData({
      ['user_information.student_number'] : e.detail.value
    })
  },
//修改信息 输入学号时触发
  stuent_number_Modify(e){
    this.setData({
      ['ModifyUser.student_number'] : e.detail.value
    })
  },
  //用户注册确认
  confirm(){
    
    wx.getUserProfile({
      desc: '展示用户信息',
      success: (res) => {
        app.globalData.nickName=res.userInfo.nickName
        app.globalData.avatarUrl=res.userInfo.avatarUrl
        app.globalData.hasUserInfo=true
        this.setData({
          avatarUrl:res.userInfo.avatarUrl,
          nickName:res.userInfo.nickName
        })
        db.collection("user").where({
          openId: this.data.user_information.openId
        }).get().then(resp=>{
          if(resp.data.length == 0){
            db.collection("user").add({
              data:{
                name: this.data.user_information.name,
                student_number: this.data.user_information.student_number,
                openId: this.data.user_information.openId,
                identity: '学生',
                avatarUrl: this.data.avatarUrl
              }
            }).then(res=>{
              Notify({ type: 'success', message: '注册成功,请重新登录' });
              wx.navigateBack()
            })
          }else{
            Notify({ type: 'success', message: '用户已存在' });
            wx.navigateBack()
          }
        }) 
      }
    })
    
    // if(!app.globalData.hasUserInformation){
    //   db.collection("user").add({
    //     data:{
    //       name: this.data.user_information.name,
    //       student_number: this.data.user_information.student_number,
    //       openId: this.data.user_information.openId,
    //       identity: '学生',
    //       avatarUrl: this.data.avatarUrl
    //     }
    //   }).then(res=>{
    //     Notify({ type: 'success', message: '注册成功,请重新登录' });
    //     this.setData({
    //       hasUserInfo: false,
    //     })
    //     this.onLoad()
    //   })
    // }else{
    //   Notify({ type: 'success', message: '用户已存在' });
    //   this.setData({hasUserInformation: true})
    // }

   
  },
  //用户修改确认
  confirmModifyUser(){
    let data = this.data.ModifyUser
    if(data.name != null && data.student_number != null){
      db.collection("user").where({
        openId: this.data.user_information.openId
      }).update({
        data: {
          name: data.name,
          student_number: data.student_number
        }
      }).then(res=>{
        Notify({ type: 'success', message: '修改成功,请重新登录' });
        this.setData({
          hasUserInfo: false,
          showModifyUser: false
        })
        this.onLoad()
      })
    }else{
      Notify({ type: 'success', message: '请输入正确的信息' });
    }
    
  },
  onLoad:function (options) {
    // let user = await wx.cloud.callFunction({ name: 'function', data: { type: "getEnv" } })
    // console.log(user)
    // // .then(res => {
    // //   // console.log(res.result.user.data[0] )
    // //   this.globalData.hasUserInformation=(res.result.user.data.length>0)?true:false
    // //   this.globalData.openId= res.result.openid
    // //   this.globalData.name = res.result.user.data[0].name
    // //   this.globalData.student_number = res.result.user.data[0].student_number
    // //   this.globalData.identity = res.result.user.data[0].identity
    // // })
    // if (user.result.user.data.length != 0){
    //   this.setData({
    //     ['user_information.openId']:user.result.user.data[0].openId,
    //     ['user_information.name']: user.result.user.data[0].name,
    //     ['user_information.student_number']: user.result.user.data[0].student_number,
    //     ['user_information.identity']:  user.result.user.data[0].identity,
    //     hasUserInformation: true,
    //     ['ModifyUser.name'] : user.result.user.data[0].name,
    //     ['ModifyUser.student_number'] : user.result.user.data[0].student_number
    //   })
    //   app.globalData.hasUserInformation=true
    //   app.globalData.openId= user.result.openid
    //   app.globalData.name = user.result.user.data[0].name
    //   app.globalData.student_number = user.result.user.data[0].student_number
    //   app.globalData.identity = user.result.user.data[0].identity
    // }else{
    //   this.setData({
    //     ['user_information.openId']:user.result.openid,
    //     hasUserInformation: false,
    //   })
    // }
    this.setData({
      avatarUrl: app.globalData.avatarUrl,
      hasUserInformation: app.globalData.hasUserInformation,
      'user_information.name': app.globalData.name,
      'user_information.identity': app.globalData.identity,
      'user_information.openId': app.globalData.openId,
      'user_information.student_number': app.globalData.student_number,
      isAdmin: app.globalData.isAdmin
    })
  },
 //退出登录
  out_login(){
    this.setData({
      hasUserInfo: false
    })
    this.onLoad()
  },
  //登录
  login(e) {
    wx.getUserProfile({
      desc: '展示用户信息',
      success: (res) => {
        app.globalData.nickName=res.userInfo.nickName
        app.globalData.avatarUrl=res.userInfo.avatarUrl
        app.globalData.hasUserInfo=true
        this.setData({
          hasUserInfo:true,
          avatarUrl:res.userInfo.avatarUrl,
          nickName:res.userInfo.nickName
        })
      }
    })
   

  },
  onShareAppMessage(res){
 
  },
  onShareTimeline(){
    
  },
  onShow(){
    this.onLoad()
  //   wx.cloud.callFunction({ name: 'function', data: { type: "getEnv" } }).then(res => {
  //     var data=res.result.user.data
  //     app.globalData.hasUserInformation=(data.length>0)?true:false
  //     app.globalData.openId=res.result.openid
  //     var isAdmin=false
  //     if(data.length>0)isAdmin=data[0].isAdmin
  //      this.setData({
  //        hasUserInformation:app.globalData.hasUserInformation,
  //       isAdmin:isAdmin
  //     })
  //   })
  }

})
function getVirtulData(year) {
  year = year || '2017';
  var date = +echarts.number.parseDate(year + '-01-01');
  var end = +echarts.number.parseDate(+year + 1 + '-01-01');
  var dayTime = 3600 * 24 * 1000;
  var data = [];
  for (var time = date; time < end; time += dayTime) {
    data.push([
      echarts.format.formatTime('yyyy-MM-dd', time),
      Math.floor(Math.random() * 10)
    ]);
  }
  return data;
}

option = {
  tooltip: {},
  visualMap: {
    min: 0,
    max: 10,
    type: 'piecewise',
    orient: 'horizontal',
    left: 'center',
    bottom: 0,
    fontWeight: 'Bold',
  },
  calendar: {
    top: 120,
    left: 30,
    right: 30,
    cellSize: ['auto', 13],
    range: '2016',
    itemStyle: {
      borderWidth: 0.5,
      color: '#fff',
      borderColor: '#ccc'
    },
    yearLabel: { show: false },
    monthLabel: {
     
      fontWeight: 'Bold',
      nameMap: ['1','2','3','4','5','6','7','8','9','10','11','12'],
      fontSize: 15,
  },
  dayLabel: {
      show: true,
      formatter: '{start}  1st',
      fontWeight: 'Bold',
      nameMap: ['日',' ',' ','三',' ',' ','六',],
      fontSize: 12
  }
  },
  series: {
    type: 'heatmap',
    coordinateSystem: 'calendar',
    data: getVirtulData('2016')
  }
};